package com.moxiao.yfjh.module.infra.controller.app.file;

import cn.hutool.core.io.IoUtil;
import com.moxiao.yfjh.framework.common.pojo.CommonResult;
import com.moxiao.yfjh.module.infra.controller.app.file.vo.AppFileUploadReqVO;
import com.moxiao.yfjh.module.infra.service.file.FileService;
import com.moxiao.yfjh.module.system.sms.utils.GreenScanUtils;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.MapUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.util.Map;
import java.util.Objects;

import static com.moxiao.yfjh.framework.common.pojo.CommonResult.error;
import static com.moxiao.yfjh.framework.common.pojo.CommonResult.success;

@Tag(name = "用户 App - 文件存储")
@RestController
@RequestMapping("/infra/file")
@Validated
@Slf4j
public class AppFileController {

    @Resource
    private FileService fileService;
    @Resource
    private GreenScanUtils greenScanUtils;
    /*** 上传的图片大小 2MB **********/
    private static final long MAX_FILE_SIZE = 2 * 1024 * 1024; // 2MB

    @PostMapping("/upload")
    @Operation(summary = "上传文件")
    public CommonResult<String> uploadFile(AppFileUploadReqVO uploadReqVO) throws Exception {
        MultipartFile file = uploadReqVO.getFile();
        String path = uploadReqVO.getPath();
        return success(fileService.createFile(file.getOriginalFilename(), path, IoUtil.readBytes(file.getInputStream())));
    }


    @PostMapping("/uploadPhotos")
    @Operation(summary = "上传照片")
    public CommonResult<String> uploadPhotos(AppFileUploadReqVO uploadReqVO) throws Exception {
        MultipartFile file = uploadReqVO.getFile();
        // 判断图片大小
        if (file.getSize() >= MAX_FILE_SIZE) {
            return error(500, "图片文件过大，头像图片大小不能超过2MB");
        }
        String path = uploadReqVO.getPath();
        String fileName = fileService.createFile(file.getOriginalFilename(), path, IoUtil.readBytes(file.getInputStream()));
        try {
           Map map = greenScanUtils.imageScan(fileName);
            if (MapUtils.isNotEmpty(map)){
                if(Objects.equals(map.get("suggestion"),"pass")){
                    return success(fileName);
                }else{
                    return error(5000,"阿里云审核失败！请重新上传");
                }
            }
        } catch (Exception e) {
            return error(500,"阿里云审核失败！请重新上传");
        }

        return success(fileName);
    }
}
